<template>
  <div class="outbox">

    <div class="sec-border"></div>
    <div class="first-border"></div>
    <div class="main">
      <div class="friend_list">
        <Add_chat_button @addChatHandler = "addChatHandler"> </Add_chat_button>
        <div style="height:95%; overflow-y: scroll;">
          <Friend_Item v-for="item in friendList" @switchDialog="switchDialog" :key="item.id" :id="item.id"
          :name="item.name" :group="false" />
          <Friend_Item v-for="item in groupList" @switchDialog="switchDialog" :key="item.id" :id="item.id" :name="item.name"
          :group="true" />
        </div>
      </div>
      <div class="chatBox">
        <div class="msgBox">
          <MsgBubble v-for="item in currentMsgList" :key="item.timestamp" :myself="item.userId == userId" :speaker="item.userId"
            :msg="item.msg" :filename =item.fileName :type="item.type" :progress="item.progress" @downloadHandler ="downloadHandler"></MsgBubble>
        </div>
        <div class="inputBox">
          <textarea required maxlength="240" v-model="inputmsg"></textarea>
        </div>
      </div>
      <ToolButton class="sendFileButton" :function-name="'SendFile'" :chinese-name="'传输文件'" @click.native="showfilebox = !showfilebox">
      </ToolButton>
      <ToolButton class="sendMsgButton" :function-name="'SendMsg'" :chinese-name="'发送消息'" @click.native="sendMsg">
      </ToolButton>
    </div>
    <fileSendingCard v-if="showfilebox" @sendFileHandler="sendFileHandler"></fileSendingCard>
  </div>
</template>
<script>
import Friend_Item from '@/components/Friend_Item.vue';
import ToolButton from '@/components/ToolButton.vue';
import MsgBubble from '@/components/MsgBubble.vue'
import axios from 'axios'
import Add_chat_button from '@/components/Add_chat_button.vue';
import fileSendingCard from '@/components/fileSendingCard.vue'
export default {
  mounted() {
    window.AboutView = this;
    let that =this
    that.userId = window.localStorage.getItem("username")
    that.username =window.localStorage.getItem("username")
    console.log(that.username)
    this.fetchMsgList();
    this.timer = window.setInterval(()=>{
      setTimeout(()=>{
        this.fetchMsgList();
      },0)
    },1000);
  },
  methods: {

    async getCoop() {
      try {
        let response = await axios.get("/api/getCoop")
        console.log("get Coop:")
        console.log(response)
        this.friendList = response.data.friendList
        this.groupList = response.data.groupList
        //TODO: 但是会导致msg列表被清空
      } catch (ERR) {
        alert(ERR)
      }

    },
    //获取 消息列表
    async fetchMsgList() {
      let response = await axios.post("/api/fetch_msg_list")

      //TODO: 差错处理
      this.updateMsgListBuffer(response.data.msg)
    },
    updateMsgListBuffer(msgList) {
      msgList.forEach(element => {
        try {
          // 输入信息--》 点击确定————》发送信息到后台-》》 更新信息列表
          let obj;
          if (element.source == "private") {
            obj = this.friendList.find(item => item.id == element.userId || item.id == element.target);//必须是深拷贝
          } else if (element.source == "group") {
            obj = this.groupList.find(item => item.id == element.userId || item.id == element.target);//必须是深拷贝
          }
          
          console.log(msgList)
          console.log(obj)
          obj.msgList.push(element)
        } catch (ERR) {
          console.warn(ERR)
        }
        this.refreshChatBox(this.displayDialog)
      });
      // this.friendList.forEach(element => {
      //   element.msgList.sort(function (a, b) { return a - b })
      // })
      console.log(this.friendList)
    },
    sendMsg() {
      if (this.inputmsg == '') {///非空校验
        alert("empty inputbox")
        return 0;
      }else{
       
        let data = {
          type:"text",
          target:this.displayDialog,
          msg:this.inputmsg
        }
        console.log(data)
        try{
            axios.request(
            {
              data:data,
              method:'post',
              url:this.displayType!='group'?'/api/send_msg':'/api/send_group_msg'
            }
          )
          
          // if(response.status == "ok"){
          //   console.log("send msg ok")
          // }else{
          //   console.warn("send msg failed")
          // }
          this.inputmsg = ""
        }catch(err){
          console.log(err)
        }
          
      }
    },
    switchDialog(ev) {
      console.log("switch to" + ev.id)
      this.displayType = ev.group == true?"group":"private"
      this.displayDialog = ev.id
      this.refreshChatBox(ev.id)
    },
    addChatHandler(param){
      if(param.chatName == this.username){
        alert("INVALID CHATNAME")
        return
      }
      if(param.ifGroup == false){
        this.friendList.push(
          {
            id:param.chatName,
            name:param.chatName,
            msgList:[]
          }
        )
      }else{
        this.groupList.push({
            id:param.chatName,
            name:param.chatName,
            msgList:[]
        })
      }
      this.switchDialog({
        id:param.chatName,
        name:param.chatName,
        group:param.isGroup
      })
    },
    refreshChatBox(id) {
      this.currentMsgList.splice(0, this.currentMsgList.length)//清空数组
      try {
        let obj = this.friendList.find(item => item.id == id) || this.groupList.find(item => item.id == id)
        obj.msgList.forEach(element => {
          this.currentMsgList.push(element)
        })
      } catch (err) {
        console.log(err)
      }
    },
    triggerFileInput(){
      document.getElementById("file").click();
      
    },
    onFilepathChange(event){
      let file = event.target.files[0]
      console.log(file)
      if(window.FileReader){
        let reader =  new FileReader()
        reader.readAsDataURL(file)
        reader.onloadend = function(e){           
          this.filepath = e.target.result
          this.filepath = e.target.result
          window.localStorage.setItem("filepath",e.target.result)
          console.log(localStorage.getItem("filepath"))
        }

      }
    },
    async sendFileHandler(path){
      if(this.displayDialog == ""){
        alert("NO CHOSEN TARGET")
        return
      }
      let data={
        target: this.displayDialog,
        filePath:path
      }
      try{
        await axios.request({
        method:"post",
        data:data,
        url:'/api/send_file'
      })
      }catch(err){
        console.log(err)
      }
      this.showfilebox =false
    },
    async downloadHandler(fileName){
      if (this.displayDialog == ''){
        alert("EMPTY SENDING TARGET")
        return;
      }
        axios.request({
          method:"post",
          data:{
            target:this.displayDialog,
            fileName:fileName,
            op:"start"
          },
          url:'/api/file_op'
        })
    }
  },
  data() {
    return {
      username: "defaultUser",
      userId: "zhier123",
      displayDialog: "",
      displayType:"",
      inputmsg: "",
      filepath:null,
      showfilebox:false,
      friendList: [
      ],
      groupList: [  
      ],
      currentMsgList: [],
  
    };
  },
  destroyed(){
    window.clearInterval(this.timer)
  },  
  components: { Friend_Item, ToolButton, MsgBubble,Add_chat_button,fileSendingCard }
}
</script>
<style scoped>
.outbox {
  perspective: 800px;
  width: 100%;
  height: 100%;

}

.main,
.first-border,
.sec-border {
  position: absolute;
  left: 46%;
  top: 45%;
  width: 70%;
  height: 90%;
}

.first-border {
  transform: translate(-50%, -50%) skew(-1deg, 4deg) rotateX(14deg) rotateY(-12deg) scale(1.05, 1.05);
  background-color: black;
}

.sec-border {
  transform: translate(-50%, -50%) skew(-2deg, 4deg) rotateX(13deg) rotateY(-12deg) scale(1.1, 1.1);
  background-color: white;
}

.main {
  background-color: rgb(134, 8, 8);
  display: flex;
  transform: translate(-50%, -50%) skew(-1deg, 3deg) rotateX(13deg) rotateY(-12deg);
}

.chatBox {
  height: 100%;
  width: 70%;
  border-left: black 5px solid;
}

.friend_list {
  height: 100%;
  width: 30%;
  border-right: 10px solid black;
  outline-color: 20px solid white;

}

.msgBox {
  width: 100%;
  height: 70%;
  border-bottom: 20px solid;
  overflow-y: scroll;
}

.sendMsgButton {
  position: absolute;
  right: 0px;
  bottom: 30px;
}

.sendFileButton {
  position: absolute;
  right: -5px;
  bottom: 120px;
  transform: rotate(-20deg)
}

.inputBox {
  height: 30%
}

.inputBox textarea {
  resize: none;
  border: none;
  background-color: transparent;
  -webkit-text-stroke: 1px black;
  -webkit-text-fill-color: white;
  font-weight: bold;
  font-size: 20px;
  color: #fff;
  padding: 10px;
  width: 80%;
  height: 100%;
  outline: none
}</style>